import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-08-11
 * Time: 22:17
 */
public class Solution {
    public int pivotIndex(int[] nums) {
        int len = nums.length;
        int[] prefix = new int[len];
        int[] suffix = new int[len];
        suffix[len-1] = nums[len-1];
        for (int i = len - 2;i >= 0;i--) {
            suffix[i] = suffix[i+1] + nums[i];
        }
        prefix[0] = nums[0];
        if (suffix[0] == prefix[0]) {
            return 0;
        }
        for (int i = 1;i < len;i++) {
            prefix[i] = prefix[i-1] + nums[i];
            if (prefix[i] == suffix[i]) {
                return i;
            }
        }
        return -1;
    }

    public int pivotIndex2(int[] nums) {
        // 总和为 total
        int total = Arrays.stream(nums).sum();
        // sum 初始化为 0, 正好模拟了中心下标位于数组最左端的情况
        int sum = 0;
        // nums[i] 左边前缀和为 sum, 右边为 total - sum - nums[i]
        // sum = total - sum - nums[i]
        for (int i = 0; i < nums.length; ++i) {
            if (2 * sum + nums[i] == total) {
                return i;
            }
            sum += nums[i];
        }
        return -1;
    }
}
